﻿//------------------------------------------------------------------------------
// <copyright file="AssessmentController.cs" company="David Martos">
//     Copyright (c) David Martos.  All rights reserved.
// </copyright>
// <summary>Assessment controller class. It contains all the logic related to this entity.</summary>
//  ----------------------------------------------------------------------------
namespace Dissemination.MVC.Controllers
{
    #region Using statements

    using System.Web.Mvc;
    using Models;
    using Repositories;
    using Dissemination.MVC.ViewModels;
    using System;
    using System.Linq;
    using Dissemination.MVC.Controllers.Extensions;
    using System.Collections.Generic;

    #endregion


    [HandleError]
    public class AssessmentController : ControllerBase
    {
        protected AssessmentRepository Repository = new AssessmentRepository();

        #region List

        //
        // GET: /Assessment?SeminarID=5

        /// <summary>
        /// Returns the view associated to the list of entities in the data source.
        /// </summary>
        /// <returns>Index view</returns>
        [Authorize(Roles = "Administrator,Reporter,Demostrator")]
        public ActionResult Index(int seminarID)
        {
            if (log.IsDebugEnabled) log.Debug("Entering Assessment list...");
            AssessmentListViewModel model = new AssessmentListViewModel();
            model.Assessments = Repository.ListBySeminarID(seminarID);
            model.ParticipantsCount = Repository.GetSeminarByID(seminarID).Participants.Count;
            if (log.IsDebugEnabled) log.Debug("Leaving Assessment list...");
            return View(model);
        }

        #endregion

        #region Details

        //
        // GET: /Assessment/Details/5

        /// <summary>
        /// Returns the view associated to the details of an entity in the data source.
        /// </summary>
        /// <param name="id">The entity id.</param>
        /// <returns>Details view</returns>
        [Authorize(Roles = "Demostrator,Administrator,Reporter")]
        public ActionResult Details(int id)
        {
            if (log.IsDebugEnabled) log.DebugFormat("Entering Assessment details with id={0}...", id);
            Assessment assessment = Repository.Get(id);

            if (assessment == null)
            {
                if (log.IsErrorEnabled) log.ErrorFormat("Assessment with id={0} not found", id);
                return View("NotFound");
            }

            if (log.IsDebugEnabled) log.DebugFormat("Leaving Assessment details with id={0}...", id);
            return assessment == null ? this.View("NotFound") : this.View(assessment);
        }

        #endregion

        #region New

        //
        // GET: /Assessment/Create?SeminarID=5

        /// <summary>
        /// 
        /// </summary>
        /// <param name="seminarID"></param>
        /// <returns></returns>
        [Authorize(Roles = "Administrator,Reporter")]
        public ActionResult Create(int seminarID)
        {
            if (log.IsDebugEnabled) log.Debug("Entering Assessment creation (GET)...");
            Seminar seminar = Repository.GetSeminarByID(seminarID);

            if (seminar.Participants.Count <= seminar.Assessments.Count)
            {
                ApplicationException exception = new ApplicationException(string.Format("The number of assesssments has reached the number of participants: ({0})", seminar.Participants.Count));
                if (log.IsErrorEnabled) log.Error(exception);
                return this.View("Error", exception);
            }
            var viewModel = new AssessmentViewModel
            {
                Assessment = new Assessment()
                {
                    Seminar = Repository.GetSeminarByID(seminarID)
                },
                Values = Repository.GetOptions(5),
            };

            if (log.IsDebugEnabled) log.Debug("Leaving Assessment creation (GET)...");

            return this.View(viewModel);
        }

        //
        // POST: /TargetArea/Create

        [HttpPost]
        [Authorize(Roles = "Administrator,Reporter")]
        public ActionResult Create(Assessment assessment)
        {
            if (log.IsDebugEnabled) log.Debug("Entering Assessment creation (POST)...");

            if (ModelState.IsValid)
            {
                var seminarID = int.Parse(RouteData.Values["seminarID"].ToString());
                assessment.Seminar = Repository.GetSeminarByID(seminarID);
                Repository.Add(assessment);
                Repository.Save();

                if (log.IsDebugEnabled) log.Debug("Leaving Assessment creation (POST)...");
                return RedirectToAction("Index", new { seminarID = seminarID });
            }

            if (log.IsDebugEnabled)
            {
                //TODO: Completar Create_Assessment
            }

            return View(assessment);
        }

        #endregion

        //
        // GET: /TargetArea/Edit/5
        [Authorize(Roles = "Administrator,Reporter")]
        public ActionResult Edit(int id)
        {

            Assessment assessment = Repository.Get(id);
            if (assessment == null)
                return View("NotFound");

            var viewModel = new AssessmentViewModel
            {
                Assessment = assessment,
                Values = Repository.GetOptions(5)
            };

            return View(viewModel);
        }

        //
        // POST: /TargetArea/Edit/5

        [HttpPost]
        [Authorize(Roles = "Administrator,Reporter")]
        public ActionResult Edit(int id, FormCollection collection)
        {
            Assessment assessment = Repository.Get(id);
            try
            {
                UpdateModel(assessment, "Assessment");
                Repository.Save();

                return RedirectToAction("Index", new { seminarID = assessment.Seminar.SeminarID });
            }
            catch
            {
                //ModelState.AddRuleViolations(FollowUp.GetRuleViolations());
                return View(assessment);
            }
        }

        //
        // GET: /Assessment/Export/5

        /// <summary>
        /// Returns the view associated with a given entity to be deleted
        /// </summary>
        /// <param name="id">The id of the existing entity</param>
        /// <returns>Delete view</returns>
        [Authorize(Roles = "Administrator,Reporter")]
        public ActionResult Export(int id)
        {
            var s = Repository.GetSeminarByID(id);
            var ta = s.TargetArea;
            var program = s.TargetArea.Program;

            List<ExcelSheetInformation> sheets = new List<ExcelSheetInformation>();
            List<ExcelCellChange> excelChanges = new List<ExcelCellChange>();

            var assessmentOrganDonor = new AssessmentLecture(s.Assessments.Average(a => a.AssessmentOrganDonorP), s.Assessments.Average(a => a.AssessmentOrganDonorC), s.Assessments.Average(a => a.AssessmentOrganDonorQ));
            var assessmentCaseStudies = new AssessmentLecture(s.Assessments.Average(a => a.AssessmentCaseStudiesP), s.Assessments.Average(a => a.AssessmentCaseStudiesC), s.Assessments.Average(a => a.AssessmentCaseStudiesQ));
            var assessmentBrainDeath = new AssessmentLecture(s.Assessments.Average(a => a.AssessmentBrainDeathP), s.Assessments.Average(a => a.AssessmentBrainDeathC), s.Assessments.Average(a => a.AssessmentBrainDeathQ));
            var assessmentSimulation = new AssessmentLecture(s.Assessments.Average(a => a.AssessmentSimulationP), s.Assessments.Average(a => a.AssessmentSimulationC), s.Assessments.Average(a => a.AssessmentSimulationQ));
            var assessmentDonor = new AssessmentLecture(s.Assessments.Average(a => a.AssessmentDonorP), s.Assessments.Average(a => a.AssessmentDonorC), s.Assessments.Average(a => a.AssessmentDonorQ));
            var assessmentApproach = new AssessmentLecture(s.Assessments.Average(a => a.AssessmentApproachP), s.Assessments.Average(a => a.AssessmentApproachC), s.Assessments.Average(a => a.AssessmentApproachQ));
            var assessmentInterviews = new AssessmentLecture(s.Assessments.Average(a => a.AssessmentInterviewsP), s.Assessments.Average(a => a.AssessmentInterviewsC), s.Assessments.Average(a => a.AssessmentInterviewsQ));
            var assessmentRetrieval = new AssessmentLecture(s.Assessments.Average(a => a.AssessmentRetrievalP), s.Assessments.Average(a => a.AssessmentRetrievalC), s.Assessments.Average(a => a.AssessmentRetrievalQ));


            excelChanges.AddRange(new List<ExcelCellChange>
                    {
                        new ExcelCellChange { Row = 2, Column = 2, Value = program.ProgramName },
                        new ExcelCellChange { Row = 3, Column = 2, Value = "ASSESSMENTS - " + s.FriendlyTitle },
                        new ExcelCellChange { Row = 5, Column = 3, Value = s.Assessments.Count },

                        new ExcelCellChange { Row = 9, Column = 3, Value = assessmentOrganDonor.Presentation },
                        new ExcelCellChange { Row = 9, Column = 4, Value = assessmentOrganDonor.Contents },
                        new ExcelCellChange { Row = 9, Column = 5, Value = assessmentOrganDonor.QuestionsAnswered },

                        new ExcelCellChange { Row = 10, Column = 3, Value = assessmentCaseStudies.Presentation },
                        new ExcelCellChange { Row = 10, Column = 4, Value = assessmentCaseStudies.Contents },
                        new ExcelCellChange { Row = 10, Column = 5, Value = assessmentCaseStudies.QuestionsAnswered },

                        new ExcelCellChange { Row = 11, Column = 3, Value = assessmentBrainDeath.Presentation },
                        new ExcelCellChange { Row = 11, Column = 4, Value = assessmentBrainDeath.Contents },
                        new ExcelCellChange { Row = 11, Column = 5, Value = assessmentBrainDeath.QuestionsAnswered },

                        new ExcelCellChange { Row = 12, Column = 3, Value = assessmentSimulation.Presentation },
                        new ExcelCellChange { Row = 12, Column = 4, Value = assessmentSimulation.Contents },
                        new ExcelCellChange { Row = 12, Column = 5, Value = assessmentSimulation.QuestionsAnswered },

                        new ExcelCellChange { Row = 13, Column = 3, Value = assessmentDonor.Presentation },
                        new ExcelCellChange { Row = 13, Column = 4, Value = assessmentDonor.Contents },
                        new ExcelCellChange { Row = 13, Column = 5, Value = assessmentDonor.QuestionsAnswered },

                        new ExcelCellChange { Row = 14, Column = 3, Value = assessmentApproach.Presentation },
                        new ExcelCellChange { Row = 14, Column = 4, Value = assessmentApproach.Contents },
                        new ExcelCellChange { Row = 14, Column = 5, Value = assessmentApproach.QuestionsAnswered },

                        new ExcelCellChange { Row = 15, Column = 3, Value = assessmentInterviews.Presentation },
                        new ExcelCellChange { Row = 15, Column = 4, Value = assessmentInterviews.Contents },
                        new ExcelCellChange { Row = 15, Column = 5, Value = assessmentInterviews.QuestionsAnswered },

                        new ExcelCellChange { Row = 16, Column = 3, Value = assessmentRetrieval.Presentation },
                        new ExcelCellChange { Row = 16, Column = 4, Value = assessmentRetrieval.Contents },
                        new ExcelCellChange { Row = 16, Column = 5, Value = assessmentRetrieval.QuestionsAnswered },

                        new ExcelCellChange { Row = 19, Column = 3, Value = s.Assessments.Average(a => a.AssessmentOrganization) },
                        new ExcelCellChange { Row = 20, Column = 3, Value = s.Assessments.Average(a => a.AssessmentTeaching) },
                        new ExcelCellChange { Row = 21, Column = 3, Value = s.Assessments.Average(a => a.AssessmentSupport) },
                        new ExcelCellChange { Row = 22, Column = 3, Value = s.Assessments.Average(a => a.AssessmentSecretariat) },

                        new ExcelCellChange { Row = 25, Column = 3, Value = s.Assessments.Average(a => a.AssessmentPreRegistration) },
                        new ExcelCellChange { Row = 26, Column = 3, Value = s.Assessments.Average(a => a.AssessmentPostRegistration) },

                        new ExcelCellChange { Row = 28, Column = 3, Value = s.Assessments.Average(a => a.AssessmentApplicability) },

                        new ExcelCellChange { Row = 30, Column = 3, Value = s.Assessments.Average(a => a.AssessmentOverall) },
                    });

            ExcelSheetInformation sheet = new ExcelSheetInformation() { Name = "Seminar assessments", Changes = excelChanges };
            sheets.Add(sheet);
            var changes = sheets.AsQueryable();
            string temporaryFileName = Server.MapPath(@"~/temp/" + Guid.NewGuid() + ".xlsx");

            if (log.IsDebugEnabled) log.DebugFormat("Leaving Program with id {0} ta...", id);

            return this.Excel("EOD_Single_Seminar_Assessments.xlsx", temporaryFileName, Server.MapPath(@"~/templates/EOD_Single_Seminar_Assessments.xlsx"), "Seminar assessments", changes);

        }

    }
}
